using System;
using System.Collections;
using System.Collections.Generic;

namespace Tycho.Parser.Peg {
    public class ChoiceProduction : Production {
        public IProduction[] Productions;

        public ChoiceProduction (params IProduction[] productions) {
            Productions = productions;
        }

        protected override Yield ReallyParse (char[] source, int index, ParseContext context, string sourceString, ParseEnvironment parseEnvironment, Func<ParseResult, Yield> continuation) {
            return Trampoline.Enumerate<IProduction> (Productions, (production, next) => {
                return production.Parse (source, index, context, sourceString, parseEnvironment, result => {
                    if (result != null) {
                        return () => continuation (result);
                    } else {
                        return next;
                    }
                });
            }, () => () => continuation (null));
        }
    }
}